import CryptoJS from 'crypto-js'
//@ts-ignore
window.cryptojs = CryptoJS;

const KEY_OBJ = {value: "test"}
export function setKey(key: string) {
    KEY_OBJ.value = key
}
export function getKey(): string | undefined {
    if (KEY_OBJ.value) {
        return KEY_OBJ.value;
    } else {
        console.error("no key set")
        return undefined;
    }
}

class MakeSecrets {
    decrypt(message: any, key?: any, option?: any):any {}
    encrypt(message: any, key?: any, option?: any): any {}
}
// const message = 
class BasicMakeSecrets extends MakeSecrets {
    decrypt(message, key?:any, option?: any): string {
        if (!key) key = getKey();
        let result = '';
        try {
            result = CryptoJS.AES.decrypt(message, key, option).toString(CryptoJS.enc.Utf8)
        } catch (e) {
            console.error(e)
            // try use JSON directly when decrypt error
            result = JSON.parse(message)
            // if can use JSON.parse correct then directly return it.
            result = message;
            // console.log("json result:", result)
        }
        return result;
    }
    encrypt(message, key?:any, option?: any): string {
        if (!key) key = getKey();
        return CryptoJS.AES.encrypt(message, key, option).toString();
    }
}

const secretMapping = {
    default: new BasicMakeSecrets(),
}
export function doMakeSecrets(type: string = "default"): MakeSecrets{
    if (secretMapping[type]) {
        return secretMapping[type]
    } else {
        console.log(`not find type:${type}, use default operation`)
        return secretMapping.default;
    }
}